package com.gzhryc.net_marketing.cloud.micro.api.controllers.cloud;

import com.gzhryc.common.ClassTools;
import com.gzhryc.common.StringTools;
import com.gzhryc.common.api.DefaultAPICodeConstants;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.net_marketing.api.protocol.account.*;
import com.gzhryc.net_marketing.cloud.account.dao.db.*;
import com.gzhryc.net_marketing.cloud.account.dao.enums.CloudPayAccountExpenditureOrderEnum;
import com.gzhryc.net_marketing.cloud.account.services.*;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.base.enums.EPayState;
import com.gzhryc.net_marketing.cloud.account.services.dto.CloudPayAccountDepositOrderSearch;
import com.gzhryc.net_marketing.cloud.account.services.dto.CloudPayAccountExpenditureOrderSearch;
import com.gzhryc.net_marketing.cloud.account.services.dto.CloudPayAccountOperateRecordSearch;
import com.gzhryc.net_marketing.cloud.account.services.dto.CloudPayAccountWithdrawOrderSearch;
import org.apache.commons.lang3.time.DateFormatUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

public class CloudPayAccountAPIController {

    static Logger log = Logger.getLogger(CloudPayAccountAPIController.class);

    @Route(value = { "/market/cloud_api/v1/payAccount/info.data" })
    public CloudPayAccountInfoResponse accountInfo(HttpServletRequest request) {
        CloudPayAccountInfoResponse apiResp = new CloudPayAccountInfoResponse(DefaultAPICodeConstants.NULL_DATA,"未找到支付账号信息");
        CloudPayAccountInfoRequest apiReq = WebUtils.getJsonRequest(request,CloudPayAccountInfoRequest.class);
        if(apiReq != null && apiReq.getBody().getAccountId() != null && StringTools.isNotBlank(apiReq.getBody().getAccountToken())){
            CloudPayAccount cloudPayAccount = CloudPayAccountService.self()
                    .getJoinByVisitToken(apiReq.getBody().getAccountId(),apiReq.getBody().getAccountToken());
            if(cloudPayAccount != null){
                apiResp.setCode(DefaultAPICodeConstants.SUCCESS,null);
                apiResp.getBody().setAccountId(cloudPayAccount.getId());
                apiResp.getBody().setMoney(cloudPayAccount.getMoney());
                apiResp.getBody().setFreezeMoney(cloudPayAccount.getFreezeMoney());
                if(cloudPayAccount.getUpdateMoneyDate() != null) {
                    apiResp.getBody().setUpdateMoneyDate(DateFormatUtils
                            .format(cloudPayAccount.getUpdateMoneyDate(), "yyyy-MM-dd HH:mm:ss"));
                }
                if(cloudPayAccount.getUpdateFreezeMoneyDate() != null) {
                    apiResp.getBody().setUpdateFreezeMoneyDate(DateFormatUtils
                            .format(cloudPayAccount.getUpdateFreezeMoneyDate(), "yyyy-MM-dd HH:mm:ss"));
                }
            }
        }
        return apiResp;
    }

    @Route(value = { "/market/cloud_api/v1/payAccount/operate/list.data" })
    public CloudPayAccountOperateListResponse findOperateList(HttpServletRequest request) {
        CloudPayAccountOperateListResponse apiResp = new CloudPayAccountOperateListResponse(DefaultAPICodeConstants.NULL_DATA,"未找到支付账号流水信息");
        CloudPayAccountOperateListRequest apiReq = WebUtils.getJsonRequest(request,CloudPayAccountOperateListRequest.class);
        if(apiReq != null && apiReq.getBody().getAccountId() != null && StringTools.isNotBlank(apiReq.getBody().getAccountToken())) {
            CloudPayAccount cloudPayAccount = CloudPayAccountService.self()
                    .getJoinByVisitToken(apiReq.getBody().getAccountId(),apiReq.getBody().getAccountToken());
            if(cloudPayAccount == null){
                apiResp.setMsg("未找到云支付账号");
                return apiResp;
            }

            Integer pageNo = apiReq.getBody().getPageNo() == null?1:apiReq.getBody().getPageNo();
            Integer pageLimit = apiReq.getBody().getPageLimit() == null?30:apiReq.getBody().getPageLimit();

            CloudPayAccountOperateRecordSearch search = new CloudPayAccountOperateRecordSearch();
            search.setAccountId(cloudPayAccount.getId());
            Long total = CloudPayAccountOperateRecordService.self().countBySearch(search);
            List<CloudPayAccountOperateRecord> data = CloudPayAccountOperateRecordService.self().findBySearch(search,pageNo,pageLimit);

            if(total > 0){
                apiResp.setCode(DefaultAPICodeConstants.SUCCESS,null);
                apiResp.getBody().setTotal(total);
                if(data != null && data.size() > 0) {
                    apiResp.getBody().setOperateItemList(new ArrayList<>());
                    for (CloudPayAccountOperateRecord record : data) {
                        CloudPayAccountOperateListResponse.OperateItem item
                                = ClassTools.copy(new CloudPayAccountOperateListResponse.OperateItem(), record);
                        item.setMoneyTypeName(record.getMoneyTypeName());
                        item.setTypeName(record.getTypeName());
                        item.setOperatorTypeName(record.getOperatorTypeName());
                        apiResp.getBody().getOperateItemList().add(item);
                    }
                }
            }
        }
        return apiResp;
    }

    @Route(value = { "/market/cloud_api/v1/payAccount/deposit/order/list.data" })
    public CloudPayAccountDepositOrderListResponse findDepositOrderList(HttpServletRequest request) {
        CloudPayAccountDepositOrderListResponse apiResp = new CloudPayAccountDepositOrderListResponse(DefaultAPICodeConstants.NULL_DATA,"未找到订单信息");
        CloudPayAccountDepositOrderListRequest apiReq = WebUtils.getJsonRequest(request,CloudPayAccountDepositOrderListRequest.class);
        log.info("云账号查询充值订单列表请求：{{0:json}}",apiReq);
        if(apiReq != null && apiReq.getBody().getAccountId() != null && StringTools.isNotBlank(apiReq.getBody().getAccountToken())) {
            CloudPayAccount cloudPayAccount = CloudPayAccountService.self()
                    .getJoinByVisitToken(apiReq.getBody().getAccountId(),apiReq.getBody().getAccountToken());
            if(cloudPayAccount == null){
                apiResp.setCode(DefaultAPICodeConstants.EXECUTE_ERROR,"未找到云支付账号");
                return apiResp;
            }

            Integer pageNo = apiReq.getBody().getPageNo() == null?1:apiReq.getBody().getPageNo();
            Integer pageLimit = apiReq.getBody().getPageLimit() == null?30:apiReq.getBody().getPageLimit();

            CloudPayAccountDepositOrderSearch search = new CloudPayAccountDepositOrderSearch();
            search.setAccountId(cloudPayAccount.getId());
            Long total = CloudPayAccountDepositOrderService.self().countBySearch(search);

            apiResp.setCode(DefaultAPICodeConstants.SUCCESS,null);
            apiResp.getBody().setTotal(total);
            if(total > 0) {
                List<CloudPayAccountDepositOrder> depositOrderList = CloudPayAccountDepositOrderService.self().findBySearch(search, pageNo, pageLimit);
                if (depositOrderList != null && depositOrderList.size() > 0){
                    apiResp.getBody().setOrderItemList(new ArrayList<>());
                    for(CloudPayAccountDepositOrder depositOrder : depositOrderList) {
                        CloudPayAccountDepositOrderListResponse.OrderItem item = new CloudPayAccountDepositOrderListResponse.OrderItem();
                        item.setTradeNo(depositOrder.getTradeNo());
                        item.setTitle(depositOrder.getTitle());
                        item.setState(depositOrder.getState());
                        item.setStateName(depositOrder.getStateName());
                        item.setCreateDate(depositOrder.getCreateDate());

                        item.setPayType(depositOrder.getPayType());
                        item.setPayTypeName(depositOrder.getPayTypeName());
                        item.setPayMoney(depositOrder.getPayMoney());
                        item.setReceiptMoney(depositOrder.getReceiptMoney());
                        item.setPayDate(depositOrder.getPayDate());

                        apiResp.getBody().getOrderItemList().add(item);
                    }
                }
            }
        }
        return apiResp;
    }

    @Route(value = { "/market/cloud_api/v1/payAccount/order/list.data" })
    public CloudPayAccountOrderListResponse findOrderList(HttpServletRequest request) {
        CloudPayAccountOrderListResponse apiResp = new CloudPayAccountOrderListResponse(DefaultAPICodeConstants.NULL_DATA,"未找到订单信息");
        CloudPayAccountOrderListRequest apiReq = WebUtils.getJsonRequest(request,CloudPayAccountOrderListRequest.class);
        log.info("云账号查询订单列表请求：{{0:json}}",apiReq);
        if(apiReq != null && apiReq.getBody().getAccountId() != null && StringTools.isNotBlank(apiReq.getBody().getAccountToken())
            && apiReq.getBody().getType() != null) {
            CloudPayAccount cloudPayAccount = CloudPayAccountService.self()
                    .getJoinByVisitToken(apiReq.getBody().getAccountId(),apiReq.getBody().getAccountToken());
            if(cloudPayAccount == null){
                apiResp.setCode(DefaultAPICodeConstants.EXECUTE_ERROR,"未找到云支付账号");
                return apiResp;
            }

            Integer pageNo = apiReq.getBody().getPageNo() == null?1:apiReq.getBody().getPageNo();
            Integer pageLimit = apiReq.getBody().getPageLimit() == null?30:apiReq.getBody().getPageLimit();

            if(apiReq.getBody().getType() == 1){
                //收入订单
                CloudPayAccountExpenditureOrderSearch search = new CloudPayAccountExpenditureOrderSearch();
                search.setPayeeAccountId(cloudPayAccount.getId());
                Long total = CloudPayAccountExpenditureOrderService.self().countBySearch(search);

                apiResp.setCode(DefaultAPICodeConstants.SUCCESS,null);
                apiResp.getBody().setTotal(total);
                if(total > 0) {
                    List<CloudPayAccountExpenditureOrder> expenditureOrderList = CloudPayAccountExpenditureOrderService.self().findBySearch(search, pageNo, pageLimit);
                    if (expenditureOrderList != null && expenditureOrderList.size() > 0){
                        apiResp.getBody().setOrderItemList(new ArrayList<>());
                        for(CloudPayAccountExpenditureOrder expenditureOrder : expenditureOrderList) {
                            CloudPayAccountOrderListResponse.OrderItem item = new CloudPayAccountOrderListResponse.OrderItem();
                            item.setTradeNo(expenditureOrder.getTradeNo());
                            item.setTitle(expenditureOrder.getTitle());
                            item.setState(expenditureOrder.getState());
                            item.setStateName(expenditureOrder.getStateName());
                            item.setCreateDate(expenditureOrder.getCreateDate());

                            item.setPayMoney(expenditureOrder.getMoney());
                            item.setPayerAccountId(expenditureOrder.getAccountId());
                            item.setPayeeAccountId(expenditureOrder.getPayeeAccountId());
                            item.setBusinessType(expenditureOrder.getBusinessType());
                            item.setBusinessTradeNo(expenditureOrder.getBusinessTradeNo());
                            apiResp.getBody().getOrderItemList().add(item);
                        }
                    }
                }
            }else if(apiReq.getBody().getType() == 2){
                //支付订单
                CloudPayAccountExpenditureOrderSearch search = new CloudPayAccountExpenditureOrderSearch();
                search.setAccountId(cloudPayAccount.getId());
                Long total = CloudPayAccountExpenditureOrderService.self().countBySearch(search);

                apiResp.setCode(DefaultAPICodeConstants.SUCCESS,null);
                apiResp.getBody().setTotal(total);
                if(total > 0) {
                    List<CloudPayAccountExpenditureOrder> expenditureOrderList = CloudPayAccountExpenditureOrderService.self().findBySearch(search, pageNo, pageLimit);
                    if (expenditureOrderList != null && expenditureOrderList.size() > 0){
                        apiResp.getBody().setOrderItemList(new ArrayList<>());
                        for(CloudPayAccountExpenditureOrder expenditureOrder : expenditureOrderList) {
                            CloudPayAccountOrderListResponse.OrderItem item = new CloudPayAccountOrderListResponse.OrderItem();
                            item.setTradeNo(expenditureOrder.getTradeNo());
                            item.setTitle(expenditureOrder.getTitle());
                            item.setState(expenditureOrder.getState());
                            item.setStateName(expenditureOrder.getStateName());
                            item.setCreateDate(expenditureOrder.getCreateDate());

                            item.setPayMoney(expenditureOrder.getMoney());
                            item.setPayerAccountId(expenditureOrder.getAccountId());
                            item.setPayeeAccountId(expenditureOrder.getPayeeAccountId());
                            item.setBusinessType(expenditureOrder.getBusinessType());
                            item.setBusinessTradeNo(expenditureOrder.getBusinessTradeNo());
                            apiResp.getBody().getOrderItemList().add(item);
                        }
                    }
                }
            }else {
                apiResp.setMsg("未知的订单类型");
            }
        }
        return apiResp;
    }

    @Route(value = { "/market/cloud_api/v1/payAccount/order/search.do" })
    public CloudPayAccountSearchOrderInfoResponse searchOrder(HttpServletRequest request){
        CloudPayAccountSearchOrderInfoResponse apiResp = new CloudPayAccountSearchOrderInfoResponse(DefaultAPICodeConstants.EXECUTE_ERROR,"查询失败");
        CloudPayAccountSearchOrderInfoRequest apiReq = WebUtils.getJsonRequest(request,CloudPayAccountSearchOrderInfoRequest.class);
        log.info("云账号支付订单查询请求：{{0:json}}",apiReq);
        if(apiReq != null && apiReq.getBody().getAccountId() != null && StringTools.isNotBlank(apiReq.getBody().getAccountToken())
                && StringTools.isNotBlank(apiReq.getBody().getBusinessTradeNo())) {

            CloudPayAccount searchAccount = CloudPayAccountService.self()
                    .getByPayToken(apiReq.getBody().getAccountId(),apiReq.getBody().getAccountToken());

            if(searchAccount == null){
                apiResp.setMsg("未找到云支付账号");
                return apiResp;
            }

            CloudPayAccountExpenditureOrder expenditureOrder = CloudPayAccountExpenditureOrderService.self()
                    .getByBusinessTradeNo(apiReq.getBody().getBusinessTradeNo());

            boolean flag = false;
            if(expenditureOrder != null){
                //检查订单是否是该账号的
                if(expenditureOrder.getPayeeAccountId().equals(searchAccount.getId())){
                    flag = true;
                }else if(expenditureOrder.getAccountId().equals(searchAccount.getId())){
                    flag = true;
                }
            }

            if(!flag){
                apiResp.setMsg("未找到订单信息");
                return apiResp;
            }

            apiResp.setCode(DefaultAPICodeConstants.SUCCESS,null);

            Integer payState = null;
            if(CloudPayAccountExpenditureOrderEnum.State.Finish.index().equals(expenditureOrder.getState())
                    || CloudPayAccountExpenditureOrderEnum.State.Settlement.index().equals(expenditureOrder.getState())){
                payState = EPayState.Success.index();
            }else if(CloudPayAccountExpenditureOrderEnum.State.WaitPay.index().equals(expenditureOrder.getState())
                    || CloudPayAccountExpenditureOrderEnum.State.Paying.index().equals(expenditureOrder.getState())){
                payState = EPayState.Wait.index();
            }else if(CloudPayAccountExpenditureOrderEnum.State.Close.index().equals(expenditureOrder.getState())){
                payState = EPayState.Close.index();
            }

            apiResp.getBody().setTradeNo(expenditureOrder.getTradeNo());
            apiResp.getBody().setBusinessType(expenditureOrder.getBusinessType());
            apiResp.getBody().setBusinessTradeNo(apiReq.getBody().getBusinessTradeNo());
            apiResp.getBody().setPayResult(payState);
            apiResp.getBody().setMoney(expenditureOrder.getMoney());
            apiResp.getBody().setAccountId(expenditureOrder.getPayeeAccountId().toString());  //收款者账号
            apiResp.getBody().setPayerId(expenditureOrder.getAccountId().toString()); //支付账号
            apiResp.getBody().setTitle(expenditureOrder.getTitle());
            apiResp.getBody().setExtContent(expenditureOrder.getExtContent());
        }else{
            apiResp.setCode(DefaultAPICodeConstants.EXECUTE_ERROR,"参数错误");
        }
        return apiResp;
    }

    @Route(value = { "/market/cloud_api/v1/payAccount/withdraw/order/list.data" })
    public CloudPayAccountWithdrawOrderListResponse findWithdrawOrderList(HttpServletRequest request) {
        CloudPayAccountWithdrawOrderListResponse apiResp = new CloudPayAccountWithdrawOrderListResponse(DefaultAPICodeConstants.NULL_DATA,"未找到订单信息");
        CloudPayAccountWithdrawOrderListRequest apiReq = WebUtils.getJsonRequest(request,CloudPayAccountWithdrawOrderListRequest.class);
        log.info("云账号查询取款订单列表请求：{{0:json}}",apiReq);
        if(apiReq != null && apiReq.getBody().getAccountId() != null && StringTools.isNotBlank(apiReq.getBody().getAccountToken())) {
            CloudPayAccount cloudPayAccount = CloudPayAccountService.self()
                    .getJoinByVisitToken(apiReq.getBody().getAccountId(),apiReq.getBody().getAccountToken());
            if(cloudPayAccount == null){
                apiResp.setCode(DefaultAPICodeConstants.EXECUTE_ERROR,"未找到云支付账号");
                return apiResp;
            }

            Integer pageNo = apiReq.getBody().getPageNo() == null?1:apiReq.getBody().getPageNo();
            Integer pageLimit = apiReq.getBody().getPageLimit() == null?30:apiReq.getBody().getPageLimit();

            CloudPayAccountWithdrawOrderSearch search = new CloudPayAccountWithdrawOrderSearch();
            search.setAccountId(cloudPayAccount.getId());
            Long total = CloudPayAccountWithdrawOrderService.self().countBySearch(search);

            apiResp.setCode(DefaultAPICodeConstants.SUCCESS,null);
            apiResp.getBody().setTotal(total);
            if(total > 0) {
                List<CloudPayAccountWithdrawOrder> depositOrderList = CloudPayAccountWithdrawOrderService.self().findBySearch(search, pageNo, pageLimit);
                if (depositOrderList != null && depositOrderList.size() > 0){
                    apiResp.getBody().setOrderItemList(new ArrayList<>());
                    for(CloudPayAccountWithdrawOrder order : depositOrderList) {
                        CloudPayAccountWithdrawOrderListResponse.OrderItem item = new CloudPayAccountWithdrawOrderListResponse.OrderItem();
                        item.setTradeNo(order.getTradeNo());
                        item.setTitle(order.getTitle());
                        item.setPayType(order.getPayType());
                        item.setMoney(order.getMoney());

                        item.setTransferType(order.getTransferType());
                        item.setTransferTypeName(order.getTransferTypeName());
                        item.setState(order.getState());
                        item.setStateName(order.getStateName());
                        item.setCreateDate(order.getCreateDate());

                        item.setReceivingAppId(order.getAppId());
                        item.setReceivingId(order.getReceivingId());
                        item.setReceivingFaceImg(order.getReceivingFaceImg());
                        item.setReceivingNickname(order.getReceivingNickname());
                        item.setReceivingPhone(order.getReceivingPhone());

                        apiResp.getBody().getOrderItemList().add(item);
                    }
                }
            }
        }
        return apiResp;
    }

    @Route(value = { "/market/cloud_api/v1/payAccount/withdraw/payee/list.data" })
    public CloudPayAccountWithdrawPayeeListResponse findWithdrawPayeeList(HttpServletRequest request) {
        CloudPayAccountWithdrawPayeeListResponse apiResp = new CloudPayAccountWithdrawPayeeListResponse(DefaultAPICodeConstants.NULL_DATA,"未找到订单信息");
        CloudPayAccountWithdrawPayeeListRequest apiReq = WebUtils.getJsonRequest(request,CloudPayAccountWithdrawPayeeListRequest.class);
        log.info("云账号查询取款人信息列表请求：{{0:json}}",apiReq);
        if(apiReq != null && apiReq.getBody().getAccountId() != null && StringTools.isNotBlank(apiReq.getBody().getAccountToken())) {
            CloudPayAccount cloudPayAccount = CloudPayAccountService.self()
                    .getJoinByVisitToken(apiReq.getBody().getAccountId(),apiReq.getBody().getAccountToken());
            if(cloudPayAccount == null){
                apiResp.setCode(DefaultAPICodeConstants.EXECUTE_ERROR,"未找到云支付账号");
                return apiResp;
            }

            List<CloudPayAccountWithdrawPayee> accountWithdrawPayeeList = CloudPayAccountWithdrawPayeeService.self()
                    .findByAccountIdAndType(apiReq.getBody().getAccountId(), apiReq.getBody().getReceivingType());
            if(accountWithdrawPayeeList != null && accountWithdrawPayeeList.size() > 0){
                apiResp.setCode(DefaultAPICodeConstants.SUCCESS,null);
                apiResp.getBody().setPayeeList(new ArrayList<>());
                for(CloudPayAccountWithdrawPayee withdrawPayee : accountWithdrawPayeeList){
                    CloudPayAccountWithdrawPayeeListResponse.Payee item = new CloudPayAccountWithdrawPayeeListResponse.Payee();
                    item.setType(withdrawPayee.getType());
                    item.setReceivingAppId(withdrawPayee.getAppId());
                    item.setReceivingId(withdrawPayee.getOpenId());
                    item.setReceivingFaceImg(withdrawPayee.getFaceImg());
                    item.setReceivingNickname(withdrawPayee.getNickname());
                    item.setReceivingPhone(withdrawPayee.getPhone());
                    item.setCreateDate(withdrawPayee.getCreateDate());
                    apiResp.getBody().getPayeeList().add(item);
                }
            }
        }
        return apiResp;
    }


}
